import React, { Component } from "react";
// 引入antd
import "antd/dist/antd.css";
import { Input, Button, List } from "antd";
// 引入 store
import store from "./store";
import {
  changeInputValueAction,
  addTaskAction,
  removeTaskAction,
} from "./store/actionCreators";

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    // 修改this指向
    this.changeInputValue = this.changeInputValue.bind(this);
    this.addTask = this.addTask.bind(this);
    this.storeChange = this.storeChange.bind(this);
    // 订阅
    store.subscribe(this.storeChange);
  }
  render() {
    return (
      <>
        {/* 输入 */}
        <header style={{ width: 300, margin: 10 }}>
          <Input
            onChange={this.changeInputValue}
            placeholder="请输入要添加的任务"
            value={this.state.inputValue}
            style={{ width: 225 }}
          />
          <Button
            onClick={this.addTask}
            type="primary"
            style={{ marginLeft: 10 }}
          >
            添加
          </Button>
        </header>
        {/* 列表 */}
        <List
          dataSource={this.state.list}
          renderItem={(item, index) => (
            <List.Item
              onClick={this.removeTask.bind(this, index)}
              style={{
                display: "flex",
                justifyContent: "space-between",
              }}
            >
              {item}{" "}
              <span style={{ color: "red", cursor: "pointer" }}>删除</span>
            </List.Item>
          )}
          bordered
          style={{ margin: "0 10px", width: "300px" }}
        />
      </>
    );
  }
  // 使得组件跟着更新
  storeChange() {
    this.setState(store.getState());
  }
  // 改变 input 的值
  changeInputValue(e) {
    const action = changeInputValueAction(e.target.value);
    store.dispatch(action);
  }
  // 添加任务
  addTask() {
    const action = addTaskAction();
    store.dispatch(action);
  }
  // 删除任务
  removeTask(index) {
    const action = removeTaskAction(index);
    store.dispatch(action);
  }
}

export default TodoList;
